//
//  XMLiveViewController.m
//  XMLiveKit
//
//  Created by lishi on 2019/5/16.
//  Copyright © 2019 lishi. All rights reserved.
//

#import "XMLiveViewController.h"

// Libs
#import "XMLiveKit.h"
#import "GPUImageBeautifyFilter.h"

@interface XMLiveViewController ()
<
    UINavigationControllerDelegate
>

{
    NSString *pathToMovie;
}

@property (nonatomic, strong) UIButton *backButton;

@property (nonatomic, strong) UIButton *endLivebutton;

@property (nonatomic, strong) UISlider *brightnessSlider;

@property (nonatomic, strong) UISlider *bilateralSlider;

@property (nonatomic, strong) UISwitch *gruopSwitch;

// 显示图
@property (nonatomic, strong) GPUImageView *liveImageView;

// 图像采集
@property (nonatomic, strong) GPUImageVideoCamera *liveVideoCamera;

@property (nonatomic, strong) GPUImageBilateralFilter *bilateralFilter;  // 双边模糊

@property (nonatomic, strong) GPUImageBrightnessFilter *brightnessFilter;  // 亮度

@property (nonatomic, strong) GPUImageMovieWriter *movieWriter;

@end

@implementation XMLiveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.liveImageView];
    [self.liveImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [self.view addSubview:self.backButton];
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(kStatusBarHeight);
        make.left.mas_equalTo(self.view).offset(15);
    }];
    
    [self.view addSubview:self.endLivebutton];
    [self.endLivebutton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(kStatusBarHeight);
        make.centerX.mas_equalTo(self.view);
    }];
    
    [self.view addSubview:self.gruopSwitch];
    [self.gruopSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(kStatusBarHeight);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    
    [self.view addSubview:self.brightnessSlider];
    [self.brightnessSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).offset(-kStatusBarHeight);
        make.right.mas_equalTo(self.view).offset(-30);
        make.left.mas_equalTo(self.view).offset(30);
    }];
    
    [self.view addSubview:self.bilateralSlider];
    [self.bilateralSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.brightnessSlider.mas_top).offset(-kStatusBarHeight);
        make.right.mas_equalTo(self.view).offset(-30);
        make.left.mas_equalTo(self.view).offset(30);
    }];
    
    [self requestAudio];
    
    [self requestAccessForVideo];
    
    [self addGroup];
    
    [self.liveVideoCamera startCameraCapture];
}

- (void)addGroup {
    // 创建滤镜：磨皮，美白，组合滤镜
    GPUImageFilterGroup *groupFilter = [[GPUImageFilterGroup alloc] init];
    
    // 磨皮滤镜
    GPUImageBilateralFilter *bilateralFilter = [[GPUImageBilateralFilter alloc] init];
    [groupFilter addTarget:bilateralFilter];
    _bilateralFilter = bilateralFilter;
    
    // 美白滤镜
    GPUImageBrightnessFilter *brightnessFilter = [[GPUImageBrightnessFilter alloc] init];
    [groupFilter addTarget:brightnessFilter];
    _brightnessFilter = brightnessFilter;
    
    // 设置滤镜组链
    [bilateralFilter addTarget:brightnessFilter];
    [groupFilter setInitialFilters:@[bilateralFilter]];
    groupFilter.terminalFilter = brightnessFilter;
    
    // 设置GPUImage响应链，从数据源 => 滤镜 => 最终界面效果
    [self.liveVideoCamera addTarget:groupFilter];
    [groupFilter addTarget:self.liveImageView];
    
}

- (void)addTarget {
    GPUImageBilateralFilter *bilateralFilter = [[GPUImageBilateralFilter alloc]init];
    //    bilateralFilter.distanceNormalizationFactor = 10;  // 模糊度数值越大越不模糊,默认值是8大于1
    // 美白滤镜-- 亮度 亮度：调整亮度（-1.0 - 1.0，默认为0.0）
    GPUImageBrightnessFilter *brightnessFilter = [[GPUImageBrightnessFilter alloc] init];
    //    brightnessFilter.brightness = 0.2;
    
    
    //4 设置处理链
    [self.liveVideoCamera addTarget:bilateralFilter];
    [bilateralFilter addTarget:brightnessFilter];
    [brightnessFilter addTarget:self.liveImageView];
    
    //    GPUImageSepiaFilter *filter = [[GPUImageSepiaFilter alloc] init];
    //    [self.liveVideoCamera addTarget:filter];
    //    [filter addTarget:self.liveImageView];
    
    //屏幕方向的检测
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
}

// 获取音频权限与资源
- (void)requestAudio {
    __weak typeof (self) weakSelf = self;
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    switch (status) {
            case AVAuthorizationStatusNotDetermined:{
                //发起授权请求
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
                    if (granted) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                        });
                    }
                }];
                break;
            }
            
            case AVAuthorizationStatusAuthorized:{
                //授权继续
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                });
            }
        default:
            break;
    }
    
}

// 获取系统的摄像头权限,获取视屏资源
- (void)requestAccessForVideo {
    __weak typeof (self) weakSelf = self;
    //判断授权状态
    AVAuthorizationStatus statues = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (statues) {
            case AVAuthorizationStatusNotDetermined:{
                //发起授权请求
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    if (granted) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                          
                        });
                    }
                }];
                
                break;
            }
            case AVAuthorizationStatusAuthorized:{
                //已授权继续
                dispatch_async(dispatch_get_main_queue(), ^{
                   
                });
                break;
            }
            
            
        default:
            break;
    }
}

//- (void)orientationDidChange:(NSNotification *)noti {
//    UIDeviceOrientation  orient = [UIDevice currentDevice].orientation;
//    self.liveVideoCamera.outputImageOrientation = (UIInterfaceOrientation)orient;
//}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)brightnessClick:(UISlider *)sender {
    _brightnessFilter.brightness = sender.value;
}

- (void)bilateralClick:(UISlider *)sender {
    CGFloat maxValue = 10;
    [_bilateralFilter setDistanceNormalizationFactor:(maxValue - sender.value)];
}

- (void)endLiveClick:(UIButton *)sender {
    [self.liveVideoCamera removeAllTargets];
    self.liveVideoCamera.audioEncodingTarget = nil;
    [_movieWriter finishRecording];
    UISaveVideoAtPathToSavedPhotosAlbum(pathToMovie, nil, nil, nil);
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)backClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)gruopClick:(UISwitch *)sender {
    // 切换美颜效果原理：移除之前所有处理链，重新设置处理链
    if (sender.on) {
        // 移除之前所有处理链
        [self.liveVideoCamera removeAllTargets];
        // 创建美颜滤镜
        GPUImageBeautifyFilter *beautifyFilter = [[GPUImageBeautifyFilter alloc] init];
        // 设置GPUImage处理链，从数据源 => 滤镜 => 最终界面效果
        [self.liveVideoCamera addTarget:beautifyFilter];
        [beautifyFilter addTarget:self.liveImageView];
        
        pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Movie.m4v"];
        unlink([pathToMovie UTF8String]);
        NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];
        _movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(480.0, 640.0)];
        _movieWriter.encodingLiveVideo = YES;
        [beautifyFilter addTarget:_movieWriter];
        self.liveVideoCamera.audioEncodingTarget = _movieWriter;
        [_movieWriter startRecording];
        
    } else {
        // 移除之前所有处理链
        [self.liveVideoCamera removeAllTargets];
        [self.liveVideoCamera addTarget:self.liveImageView];
    }
}

- (UIButton *)endLivebutton {
    if (!_endLivebutton) {
        _endLivebutton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_endLivebutton setTitle:@"退出直播" forState:UIControlStateNormal];
        [_endLivebutton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [_endLivebutton addTarget:self action:@selector(endLiveClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _endLivebutton;
}

- (UISlider *)brightnessSlider {
    if (!_brightnessSlider) {
        _brightnessSlider = [[UISlider alloc] init];
        [_brightnessSlider addTarget:self action:@selector(brightnessClick:) forControlEvents:UIControlEventValueChanged];
    }
    return _brightnessSlider;
}

- (UISlider *)bilateralSlider {
    if (!_bilateralSlider) {
        _bilateralSlider = [[UISlider alloc] init];
        [_bilateralSlider addTarget:self action:@selector(bilateralClick:) forControlEvents:UIControlEventValueChanged];
        _bilateralSlider.minimumValue = 1;
        _bilateralSlider.maximumValue = 10;
    }
    return _bilateralSlider;
}

- (GPUImageVideoCamera *)liveVideoCamera {
    if (!_liveVideoCamera) {
        _liveVideoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset1280x720 cameraPosition:AVCaptureDevicePositionFront];
        _liveVideoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
        //防止允许声音通过的情况下，避免录制第一帧黑屏闪屏
        [_liveVideoCamera addAudioInputsAndOutputs];
        
        // 摄像头左右相反
        _liveVideoCamera.horizontallyMirrorFrontFacingCamera = YES;
        _liveVideoCamera.horizontallyMirrorRearFacingCamera = NO;
    }
    return _liveVideoCamera;
}

- (GPUImageView *)liveImageView {
    if (!_liveImageView) {
        _liveImageView = [[GPUImageView alloc] init];
        //GPUImageView填充模式
        _liveImageView.fillMode = kGPUImageFillModePreserveAspectRatioAndFill;
    }
    return _liveImageView;
}

- (UISwitch *)gruopSwitch {
    if (!_gruopSwitch) {
        _gruopSwitch = [[UISwitch alloc] init];
        [_gruopSwitch addTarget:self action:@selector(gruopClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _gruopSwitch;
}

- (UIButton *)backButton {
    if (!_backButton) {
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backButton setTitle:@"返回" forState:UIControlStateNormal];
        [_backButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}

@end
